import http from '../utils/http.js'
import KeyboardAudio from '../utils/keyboardAudio.js'
import specialChars from '../utils/specialChars.js'

export const dictationPracticeMixin = {
  data() {
    return {
      remainTimeOfNext: -1,
      currentSentenceIndex: 0,
      isPlaying: false,
      // 练习相关数据
      sentenceItems: [], // 句子项（包括单词和标点）
      correctWords: [], // 正确单词
      userInputs: [], // 用户输入
      currentFocusedIndex: -1, // 当前聚焦的输入框索引
      hintCount: 0, // 提示次数
      isCompleted: false, // 是否完成
      sentenceEndTime: 0, // 句子结束时间
      validationStates: [], // 验证状态数组，用于存储每个输入框的状态
      wordPhonetic: {},
      autoAdvance: false, // 是否自动跳转到下一句
      showPhonetic: true,
      completionTimer: null, // 完成计时器,
      completionInterval: null
    }
  },
  computed: {
    currentSentence() {
      if (!this.lesson || !this.lesson.content || this.lesson.content.length === 0) {
        return { english: '', chinese: '' }
      }
      this.$nextTick(() => {
        this.initExercise()
      })
      return this.lesson.content[this.currentSentenceIndex] || { english: '', chinese: '' }
    }
  },
  async mounted() {
    // 从localStorage加载自动跳转设置
    this.loadAutoAdvanceSetting()
    this.loadShowPhoneticSetting()

    KeyboardAudio.register('keyDown', 'keyDown')
    KeyboardAudio.register('Enter', this.togglePlayback)
    // 注册空格键
    KeyboardAudio.register(' ', this.togglePlayback)
    KeyboardAudio.register('ArrowLeft', () => {
      this.playPrevious()
      this.togglePlayback()
    })
    KeyboardAudio.register('ArrowRight', () => {
      this.playNext()
      this.togglePlayback()
    })
    KeyboardAudio.register('Control', this.showHint)
    KeyboardAudio.register('[', this.resetExercise)
    const lessonId = this.$route.params.id
    await this.loadLesson(lessonId)

    // Check for sentence_id parameter and set current sentence index
    const sentenceId = this.$route.query.sentence_id
    if (sentenceId && !isNaN(sentenceId) && sentenceId > 0) {
      // Convert to 0-based index
      const index = parseInt(sentenceId) - 1
      // Make sure it's within bounds
      if (index < this.lesson.content.length) {
        this.currentSentenceIndex = index
        // Initialize exercise for the specified sentence
        this.$nextTick(() => {
          this.initExercise()
        })
      }
    }
    this.focusNextInput(-1)
  },
  beforeUnmount() {
    KeyboardAudio.destroy()
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }
    // 清除计时器
    if (this.completionTimer) {
      clearTimeout(this.completionTimer)
    }
    if (this.completionInterval) {
      clearInterval(this.completionInterval)
    }
  },
  methods: {
    getPhonetic(item) {
      if (this.wordPhonetic[item]?.phonetic) return
      // 如果item.text包含非英文字符，直接返回
      if (/[0-9]/.test(item.text)) {
        return
      }
      http.get(`/vocabulary/phonetic/${item.text}`).then((res) => {
        if (!res.phonetic) return
        let phonetic = res.phonetic
        // 取'美'的前面部分
        phonetic = phonetic.split('美')[0]
        // 清空全部汉字
        phonetic = phonetic.replace('英:', '')
        phonetic = phonetic.replace(/[\u4e00-\u9fa5]/g, '')
        phonetic = phonetic.trimStart().trimEnd()
        this.wordPhonetic[item.text] = phonetic
      })
    },
    calcWidth(chars) {
      const width = `width: ${Math.max(chars.length * 24, 60)}px`
      return width
    },
    initExercise() {
      this.focusNextInput(-1)
      // 清除之前的计时器
      if (this.completionTimer) {
        clearTimeout(this.completionTimer)
        this.completionTimer = null
      }
      if (this.completionInterval) {
        clearInterval(this.completionInterval)
        this.completionInterval = null
      }

      if (!this.currentSentence) {
        return
      }
      // 获取当前句子的英文文本
      const sentenceText = this.currentSentence.english

      // 分割句子为单词和标点符号，使用空格分割并去除末尾标点
      const tokens = this.tokenizeSentence(sentenceText)

      // 创建句子项数组
      this.sentenceItems = []
      this.correctWords = []

      let wordIndex = 0
      tokens.forEach((token) => {
        // 如果是一个纯数字，则不处理
        if (!isNaN(token) && token.length > 0) {
          this.sentenceItems.push({
            type: 'punctuation',
            text: token
          })
          return
        }
        // 如果是"Lesson", 则不处理
        if (token === 'Lesson') {
          this.sentenceItems.push({
            type: 'punctuation',
            text: token
          })
          return
        }
        // 判断是单词还是标点符号
        if (this.isWord(token)) {
          // 单词
          let item = {
            type: 'word',
            text: token,
            wordIndex: wordIndex
          }
          this.getPhonetic(item)
          this.sentenceItems.push(item)
          this.correctWords.push(token)
          wordIndex++
        } else {
          // 标点符号
          this.sentenceItems.push({
            type: 'punctuation',
            text: token
          })
        }
      })

      // 初始化用户输入数组
      this.userInputs = new Array(this.correctWords.length).fill('')

      // 初始化验证状态数组
      this.validationStates = new Array(this.correctWords.length).fill('')

      this.hintCount = 0
      this.isCompleted = false
    },

    // 将句子分割为单词和标点符号的函数
    tokenizeSentence(sentence) {
      // 先按空格分割
      const parts = sentence.split(' ')
      const tokens = []

      parts.forEach((part) => {
        // 移除末尾的标点符号作为单词
        const word = specialChars.indexOf(part) > -1 ? part : part.replace(/[.!?,"'();:]$/, '')
        if (word) {
          tokens.push(word)
        }

        // 如果原部分包含末尾标点符号，则单独作为一个token
        const punctuationMatch = part.match(/[.!?,"'();:]$/)
        if (punctuationMatch && specialChars.indexOf(part) === -1) {
          tokens.push(punctuationMatch[0])
        }
      })

      return tokens
    },

    // 判断是否为单词的函数
    isWord(token) {
      // 不是标点符号的就是单词
      return !/[.!?,"'();:-]/.test(token)
    },

    playPrevious() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--
        this.initExercise()
      }
    },

    togglePlayback() {
      this.remainTimeOfNext = -1
      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.playCurrentSentence()
      }
    },

    playNext() {
      this.remainTimeOfNext = -1
      if (this.currentSentenceIndex < this.lesson.content.length - 1) {
        this.currentSentenceIndex++
        this.initExercise()
      }
    },

    playCurrentSentence() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        this.audio.currentTime = sentence.startTime
        this.sentenceEndTime = sentence.endTime
        this.audio.play()
        this.isPlaying = true
      }
    },

    pauseAudio() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
    },

    onAudioTimeUpdate() {
      // 检查是否到达句子结束时间
      if (this.isPlaying && this.audio && this.audio.currentTime >= this.sentenceEndTime) {
        this.audio.pause()
        this.isPlaying = false
      }
    },

    onAudioEnded() {
      this.isPlaying = false
    },

    changeSpeed(speed) {
      if (this.audio) {
        this.audio.playbackRate = speed
      }
    },

    // 检查是否完成练习
    checkCompletion() {
      // 检查用户输入是否正确
      const allCorrect = this.userInputs.every(
        (input, index) => input.toLowerCase().trim() === this.correctWords[index].toLowerCase()
      )

      if (allCorrect && this.userInputs.length > 0) {
        KeyboardAudio.play('success')
        this.isCompleted = true

        // 如果启用了自动跳转功能，则3秒后自动跳转到下一句
        if (this.autoAdvance) {
          this.remainTimeOfNext <= -1 ? (this.remainTimeOfNext = 3) : this.remainTimeOfNext--
          this.completionInterval = setInterval(() => {
            this.remainTimeOfNext--
          }, 1000)
          this.completionTimer = setTimeout(() => {
            if (this.currentSentenceIndex < this.lesson.content.length - 1) {
              this.playNext()
              clearInterval(this.completionInterval)
              this.togglePlayback()
            }
          }, 3000)
        }
      }
    },

    fillAllWords() {
      // 自动填写所有单词
      this.correctWords.forEach((word, index) => {
        this.userInputs[index] = word
        // 更新验证状态为成功
        this.validationStates[index] = 'success'
      })

      // 聚焦到最后一个输入框
      if (this.correctWords.length > 0) {
        this.$nextTick(() => {
          const lastIndex = this.correctWords.length - 1
          const inputs = document.querySelectorAll('.word-item input')
          if (inputs[lastIndex]) {
            inputs[lastIndex].focus()
            this.currentFocusedIndex = lastIndex
          }
        })
      }

      this.checkCompletion()
    },

    showHint() {
      // 提供提示：逐个显示当前聚焦输入框对应单词的字母
      if (this.currentFocusedIndex >= 0 && this.currentFocusedIndex < this.correctWords.length) {
        const correctWord = this.correctWords[this.currentFocusedIndex]
        const currentUserInput = this.userInputs[this.currentFocusedIndex] || ''

        // 如果已经显示了完整单词，则不处理
        if (currentUserInput.length < correctWord.length) {
          // 显示下一个字母
          this.userInputs[this.currentFocusedIndex] = correctWord.substring(0, currentUserInput.length + 1)
          // 更新验证状态
          this.validationStates[this.currentFocusedIndex] = this.validateInput(
            this.userInputs[this.currentFocusedIndex],
            this.currentFocusedIndex
          )

          // 如果提示后单词完整且正确，移动到下一个输入框
          if (this.userInputs[this.currentFocusedIndex].toLowerCase() === correctWord.toLowerCase()) {
            this.focusNextInput(this.currentFocusedIndex)
          }
        }
      }
      this.checkCompletion()
    },

    resetExercise() {
      this.userInputs = new Array(this.correctWords.length).fill('')
      this.hintCount = 0
      this.isCompleted = false
      // 重置验证状态
      this.validationStates = new Array(this.correctWords.length).fill('')
      this.focusNextInput(-1)
    },

    // 处理用户输入事件
    handleInput(value, wordIndex) {
      if (this.userInputs[wordIndex].startsWith(' ') || this.userInputs[wordIndex].endsWith(' ')) {
        this.userInputs[wordIndex] = value.trimStart()
        this.userInputs[wordIndex] = value.trimEnd()
        return this.handleInput(this.userInputs[wordIndex], wordIndex)
      }
      if (this.userInputs[wordIndex].indexOf('[') > -1) {
        this.userInputs[wordIndex] = value.replace('[', '')
        return this.handleInput(this.userInputs[wordIndex], wordIndex)
      }
      // 更新验证状态
      this.validationStates[wordIndex] = this.validateInput(value, wordIndex)

      // 检查单词是否完全正确输入
      const correctWord = this.correctWords[wordIndex]
      if (value.toLowerCase().trim() === correctWord.toLowerCase()) {
        // 单词完全正确，切换到下一个输入框
        this.focusNextInput(wordIndex)
      }

      this.checkCompletion()
    },

    // 聚焦到下一个输入框
    focusNextInput(currentIndex) {
      // 查找下一个单词输入框
      const nextIndex = currentIndex + 1
      if (nextIndex < this.correctWords.length) {
        // 使用 $nextTick 确保 DOM 更新后再设置焦点
        this.$nextTick(() => {
          // 通过DOM查询方式获取下一个输入框
          const inputs = document.querySelectorAll('.word-item input')
          if (inputs[nextIndex]) {
            inputs[nextIndex].focus()
            // 同时更新当前聚焦索引
            this.currentFocusedIndex = nextIndex
          }
        })
      }
    },

    // 验证输入的字符
    validateInput(value, wordIndex) {
      const correctWord = this.correctWords[wordIndex]
      if (!correctWord) return ''

      // 如果输入为空，不应用任何样式
      if (!value) {
        return ''
      }

      // 如果输入长度超过正确单词长度，标记为错误
      if (value.length > correctWord.length) {
        return 'error'
      }

      // 检查每个输入的字符是否匹配
      for (let i = 0; i < value.length; i++) {
        if (i < correctWord.length && value[i].toLowerCase() !== correctWord[i].toLowerCase()) {
          if (value.indexOf(' ') === -1) KeyboardAudio.play('warning')
          return 'error' // 字符不匹配
        }
      }

      // 所有已输入字符都正确
      if (value.length === correctWord.length) {
        KeyboardAudio.play('correct')
        return 'success' // 完全匹配
      } else {
        return 'progress' // 部分匹配
      }
    },
    saveShowPhoneticSetting() {
      localStorage.setItem('dictationShowPhonetic', JSON.stringify(this.showPhonetic))
    },
    // 保存自动跳转设置到localStorage
    saveAutoAdvanceSetting() {
      localStorage.setItem('dictationAutoAdvance', JSON.stringify(this.autoAdvance))
    },
    loadShowPhoneticSetting() {
      const savedSetting = localStorage.getItem('dictationShowPhonetic')
      if (savedSetting !== null) {
        this.showPhonetic = JSON.parse(savedSetting)
      }
    },
    // 从localStorage加载自动跳转设置
    loadAutoAdvanceSetting() {
      const savedSetting = localStorage.getItem('dictationAutoAdvance')
      if (savedSetting !== null) {
        this.autoAdvance = JSON.parse(savedSetting)
      }
    }
  }
}
